#ifndef RTSP_SERVICE_RTSP_SERVICE_H
#define RTSP_SERVICE_RTSP_SERVICE_H
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "rtp_unit.h"
#include "TWList.h"
#include "str/PBufStr.h"
#include "BSocketFile.h"
#include "ABMemoryPool.h"
#include "rtsp_unit.h"
#include "TThreadPool.h"

#define RTSPSTRVICE_RET_ERR_SOCKET -2
#define RTSPSTRVICE_RET_ERR_BIND -3
#define RTSPSERVICE_ERT_ERR_LISTEN -4
#define RTSPSERVICE_ERT_ERR_SET -5

#define RTSPSTRVICE_RET_ERROR -1
#define RTSPSERVICE_RET_SUCCEED 0
#define RTSPSERVICE_RET_WAIT 1
typedef struct PortMap {
    unsigned short startport;
    unsigned short pair_num;
    unsigned char *map;
} PortMap;
//RTSP服务器
typedef struct RTSPService {
    int s_socket;                       //服务器套接字
    struct sockaddr_in s_in;            //服务器套接字信息
    int a_socket;                       //接受连接套接字
    struct sockaddr_in a_in;            //接受套接字信息
    ABMemoryPool rtsp_memory;           //内存池，分配RTST单元内存
    ABMemoryPool thread_memory;         //线程单元内存池
    ABMemoryPool task_memory;           //任务单元内存池
    ABMemoryPool list_node_memory;      //RTSP/RTP共用列表节点内存池
    ABMemoryPool rtpunit_memory;        //RTP单元内存池
    ABMemoryPool rtpuser_memory;        //RTP单元内存池

    TWListHead rtsp_list;               //RTSP单元列表
    pthread_mutex_t rtp_list_lock;      //RTP单元操作锁
    TWListHead rtp_resource_list;       //RTP单元列表

    TThreadPool thread_pool;            //线程池
    PortMap portmap;                    //端口池
    struct RTSPService *self;           //自己的地址
} RTSPService;


//初始化非阻塞套接字
extern int RTSPService_init(RTSPService *service, char *ip, unsigned int port, int link_num, unsigned short start_port,
                            unsigned short port_pair);

//接受非阻塞客户连接
extern int RTSPService_accept(RTSPService *service);

//接受连接任务
extern int RTSPService_accept_task(RTSPService *service);

//申请RTP资源
extern TWListNode *RTSPService_RTPUnit_get(struct RTSPService *service, void *rtspunit);

//释放RTP资源
extern int RTSPService_RTPUnit_delete(RTSPService *service, TWListNode *node);

//申请端口
extern unsigned short RTSPService_PortMap_malloc(RTSPService *service);

//释放端口
extern void RTSPService_PortMap_free(RTSPService *service, unsigned short port);

extern struct RTPUser *RTSPService_RTPUser_malloc(RTSPService *service);

extern void RTSPService_RTPUser_free(RTSPService *service, struct RTPUser *user);

#endif //RTSP_SERVICE_RTSP_SERVICE_H
